from flask import current_app
from flask import g, jsonify
from flask import request
from flask import session

from Program import db, constants
from Program.models import Category, News
from Program.utils.pic_storage import pic_storage
from Program.utils.response_code import RET
from . import profile_blu
from flask import render_template
from Program.utils.common import user_login_data


@profile_blu.route('/base_info', methods=["POST", "GET"])
@user_login_data
def user_base_info():
    """展示用户基本资料"""
    # GET:获取用户基本资料
    user = g.user
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("profile/user_base_info.html", data=data)

    # POST: 请求修改用户基本资料

    """
    1.获取参数
        1.1 signature:个性签名， nick_name:昵称， gender:性别，user:当前登录用户
    2.校验参数
        2.1 非空判断
        2.2 gender in ['MAN','WOMAN']
    3.逻辑处理
        3.0 将获取到的属性保存到当前登录的用户中
        3.1 更新session中的nick_name数据
        3.2 将用户对象保存回数据库
    4.返回值
    """

    # 1.1 signature:个性签名， nick_name:昵称， gender:性别，user:当前登录用户
    params_dict = request.json
    signature = params_dict.get("signature")
    nick_name = params_dict.get("nick_name")
    gender = params_dict.get("gender")

    # 2.1 非空判断
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 2.2 用户是否登录判断
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 2.3 gender in ['MAN','WOMAN']
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="action参数错误")

    # 3.0 将获取到的属性保存到当前登录的用户中
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    # 3.1 更新session中的nick_name数据
    session["nick_name"] = nick_name
    # 3.2 将用户对象保存回数据库

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户对象异常")

    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="修改用户基本资料成功")


# 127.0.0.1:5000/user/info
@profile_blu.route('/info')
@user_login_data
def user_info():
    """展示用户个人中心页面"""
    # 1.获取用户对象
    user = g.user
    # 2.组织数据
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("profile/user.html", data=data)


@profile_blu.route("/user_pic_info", methods=['POST', "GET"])
@user_login_data
def user_pic_info():
    """修改用户头xiang"""
    # 1.判断用户是否登陆
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pic_info.html", data={'user_info': user.to_dict()})
    # 2.获取图片文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件失败")
    # 3.尝试将文件上传到
    try:
        url = pic_storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.THIRDERR,errmsg="上传图片错误")
    # 4.将图片更新到用户模型中
    user.avatar_url = url
    # 5.保存提交
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")
    # 6.返回结果
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    """修改密码后端接口"""
    user = g.user
    # GET请求：返回修改密码页面
    if request.method == 'GET':
        return render_template("profile/user_pass_info.html")

    # POST请求：修改用户密码接口
    """
    1.获取参数
        1.1 old_password:旧密码，new_password: 新密码，user:用户对象
    2.校验参数
        2.1 非空判断
    3.逻辑处理
        3.0 对旧密码进行校验
        3.1 将新密码赋值到user对象password属性上
        3.2 保存回数据库
    4.返回值
    """
    # 1.1 old_password:旧密码，new_password: 新密码，user:用户对象
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2.1 非空判断
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 3.0 对旧密码进行校验
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="旧密码填写错误")

    # 3.1 将新密码赋值到user对象password属性上
    user.password = new_password
    # 3.2 保存回数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户密码异常")
    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="修改密码成功")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    """用户收藏页面"""
    # 获取页数
    p = request.args.get('p',1)
    # 校验
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user
    collections = []
    current_app = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 创建数据对象
    collection_dict_list=[]
    for news in collections if collections else None:
        collection_dict_list.append(news.to_dict())
    data = {
        "total_page": total_page, "current_page": current_page, "collections": collection_dict_list
    }
    return render_template('profile/user_collection.html',data = data)


@profile_blu.route('/news_release',methods=['POST',"GET"])
@user_login_data
def news_release():
    """新闻发布"""
    # 1.实现分类列表展示
    if request.method == "GET":
        categories = []
        try:
            # 获取所有的分类数据
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 定义列表保存分类数据
        categories_dicts = []

        for category in categories:
            # 获取字典
            cate_dict = category.to_dict()
            # 拼接内容
            categories_dicts.append(cate_dict)

        # 移除'最新'分类
        categories_dicts.pop(0)
        # 返回内容
        return render_template('profile/user_news_release.html', data={"categories": categories_dicts})

    # POST 提交，执行发布新闻操作

    # 1. 获取要提交的数据
    title = request.form.get("title",'')
    source = "个人发布"
    digest = request.form.get("digest",'')
    content = request.form.get("content",'')
    index_image = request.files.get("index_image",'')
    category_id = request.form.get("category_id",'')
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 将标题图片上传到七牛
    try:
        key = pic_storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 初始化新闻模型，并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


# 发布新闻列表
@profile_blu.route('/news_list')
@user_login_data
def news_list():
    # 获取页数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user
    news_list = []
    current_app = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_list = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_list:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    print(data['news_list'])
    return render_template('profile/user_news_list.html',data = data)


# 用户关注列表
@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('profile/user_follow.html', data=data)
